
package com.hlkj.pay.app.merchant.ext.impl.alipay;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Repository;

import com.alipay.api.AlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipaySecurityRiskComplaintInfoBatchqueryRequest;
import com.alipay.api.request.AlipaySecurityRiskComplaintInfoQueryRequest;
import com.alipay.api.request.AlipaySecurityRiskComplaintProcessFinishRequest;
import com.alipay.api.request.AlipaySecurityRiskComplaintReplySendRequest;
import com.alipay.api.response.AlipaySecurityRiskComplaintInfoBatchqueryResponse;
import com.alipay.api.response.AlipaySecurityRiskComplaintInfoQueryResponse;
import com.alipay.api.response.AlipaySecurityRiskComplaintProcessFinishResponse;
import com.alipay.api.response.AlipaySecurityRiskComplaintReplySendResponse;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.PageResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.framework.extension.annotation.Extension;
import com.hlkj.pay.app.merchant.ext.ChannelMerchantComplaintExtPt;
import com.hlkj.pay.app.merchant.ext.MerchantExtConstant;
import com.hlkj.pay.app.merchant.ext.dto.order.ChannelComplaintOrderContext;
import com.hlkj.pay.app.merchant.ext.impl.alipay.dto.AliComplaintNotifyResp;
import com.hlkj.pay.app.merchant.ext.impl.alipay.dto.AlipayConfig;
import com.hlkj.pay.app.merchant.ext.impl.alipay.handler.AliPayCommonParamsHandle;
import com.hlkj.pay.app.merchant.ext.impl.wxpay.dto.OrderComplaintMediaDto;
import com.hlkj.pay.app.merchant.ext.impl.wxpay.dto.WxComplaintDetailResp;
import com.hlkj.pay.app.merchant.ext.impl.wxpay.dto.WxComplaintHistoryDto;
import com.hlkj.pay.common.MerchantResultCode;
import com.hlkj.pay.dto.order.ComplaintOrderQueryDto;
import com.hlkj.pay.dto.order.notify.OrderComplaintNotifyDto;
import com.hlkj.pay.infrastructure.model.order.OrderComplaintChannelDO;
import com.hlkj.pay.infrastructure.model.order.OrderComplaintDO;
import com.hlkj.pay.infrastructure.model.order.OrderComplaintHistoryDO;
import com.hlkj.pay.infrastructure.model.order.PayOrderDO;
import com.hlkj.pay.service.order.IOrderComplaintService;
import com.hlkj.pay.service.order.IPayOrderService;
import com.hlkj.pay.util.DateUtils;
import com.ijpay.alipay.AliPayApi;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 支付宝订单投诉操作
 * 
 * @author HlpayTeam
 * @date 2024/10/10 13:51
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Extension(bizId = MerchantExtConstant.CHANNEL_ALI_PAY)
public class AliMerchantComplaintExtPt implements ChannelMerchantComplaintExtPt {

    private final AliPayCommonParamsHandle aliPayCommonParamsHandle;
    private final IPayOrderService payOrderService;
    private final IOrderComplaintService orderComplaintService;
    @Override
    public CommonResult<List<OrderComplaintDO>> queryComplaintPage(ChannelComplaintOrderContext channelComplaintOrderContext) {

        log.info("AliMerchantComplaintExtPt  queryComplaintPage 请求参数:{}", JsonUtils.toJsonString(channelComplaintOrderContext));
        OrderComplaintChannelDO orderComplaintChannelDO = channelComplaintOrderContext.getOrderComplaintChannelDO();
        // 支付宝配置信息
        CommonResult<AlipayConfig> alipayConfigCommonResult  = aliPayCommonParamsHandle.aliComplaintConfig(orderComplaintChannelDO,
                channelComplaintOrderContext.isTest());
        if (!alipayConfigCommonResult.isSuccess()) {
            channelComplaintOrderContext.setRemark(alipayConfigCommonResult.getMsg());
            channelComplaintOrderContext.setProcessStatus(false);
        }

        try {
            // 获取AlipayClient
            AlipayClient client = aliPayCommonParamsHandle.initClient(alipayConfigCommonResult.getData());
            // 构造请求参数以调用接口
            AlipaySecurityRiskComplaintInfoBatchqueryRequest request = new AlipaySecurityRiskComplaintInfoBatchqueryRequest();
            AlipaySecurityRiskComplaintInfoBatchqueryModel model = new AlipaySecurityRiskComplaintInfoBatchqueryModel();
            // 设置当前页码
            model.setCurrentPageNum(1L);
            // 设置每页条数
            model.setPageSize(100L);
            // 时间区间走定时任务
            if(channelComplaintOrderContext.getStartTime() != null && channelComplaintOrderContext.getEndTime() != null){
                model.setGmtComplaintStart(channelComplaintOrderContext.getStartTime());
                model.setGmtComplaintEnd(channelComplaintOrderContext.getEndTime());
            }
            request.setBizModel(model);

            log.info("支付宝查询投诉列表请求参数:{}", JSONUtil.toJsonStr(model));
            AlipaySecurityRiskComplaintInfoBatchqueryResponse response = client.execute(request);
            log.info("支付宝查询投诉列表返回参数:{}", JSONUtil.toJsonStr(response));

            if (response.isSuccess()) {
                List<ComplaintInfoQueryResponse> pageResps = response.getComplaintList();
                if(CollUtil.isNotEmpty(pageResps)){
                    List<OrderComplaintDO> orderComplaintDOS = new ArrayList<>();
                    for(ComplaintInfoQueryResponse detailResp:pageResps){
                        OrderComplaintDO orderComplaint = formatDetailResp(detailResp,orderComplaintChannelDO);
                        orderComplaintDOS.add(orderComplaint);
                    }
                    return CommonResult.success(orderComplaintDOS);
                }
            }else{
                channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
                channelComplaintOrderContext.setRemark(response.getSubMsg());
            }

        }catch (Exception e) {
            log.error("支付宝查询投诉列表请求失败 message:{}",  e);
            channelComplaintOrderContext.setRemark("支付宝查询投诉列表请求失败,失败信息" + e.getMessage());
            channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
        }
        return CommonResult.success();

    }

    @Override
    public CommonResult<OrderComplaintNotifyDto> queryComplaintDetail(ChannelComplaintOrderContext channelComplaintOrderContext) {

        log.info("支付宝查询投诉详情 请求参数:{}", JsonUtils.toJsonString(channelComplaintOrderContext));
        OrderComplaintChannelDO orderComplaintChannelDO = channelComplaintOrderContext.getOrderComplaintChannelDO();
        OrderComplaintDO orderComplaintDO = channelComplaintOrderContext.getOrderComplaintDO();
        // 支付宝配置信息
        CommonResult<AlipayConfig> alipayConfigCommonResult  = aliPayCommonParamsHandle.aliComplaintConfig(orderComplaintChannelDO,
                channelComplaintOrderContext.isTest());
        if (!alipayConfigCommonResult.isSuccess()) {
            channelComplaintOrderContext.setRemark(alipayConfigCommonResult.getMsg());
            channelComplaintOrderContext.setProcessStatus(false);
        }
        try {
            // 获取AlipayClient
            AlipayClient client = aliPayCommonParamsHandle.initClient(alipayConfigCommonResult.getData());

            AlipaySecurityRiskComplaintInfoQueryRequest request = new AlipaySecurityRiskComplaintInfoQueryRequest();
            AlipaySecurityRiskComplaintInfoQueryModel model = new AlipaySecurityRiskComplaintInfoQueryModel();
            // 设置投诉主表主键id
            model.setComplainId(orderComplaintDO.getComplaintId());
            request.setBizModel(model);

            log.info("支付宝查询投诉详情请求参数:{}", JSONUtil.toJsonStr(model));
            AlipaySecurityRiskComplaintInfoQueryResponse response = client.execute(request);
            log.info("支付宝查询投诉详情返回参数:{}", JSONUtil.toJsonStr(response));

            if (response.isSuccess() ) {
                OrderComplaintDO orderComplaint = formatDetailResp(response,null);
                BeanUtil.copyProperties(orderComplaint,orderComplaintDO, CopyOptions.create().ignoreNullValue());
                channelComplaintOrderContext.setOrderComplaintDO(orderComplaintDO);
                log.info("支付宝查询投诉详情 返回参数:{}", JsonUtils.toJsonString(orderComplaintDO));
            }else{
                channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
                channelComplaintOrderContext.setRemark(response.getSubMsg());
            }

        }catch (Exception e) {
            log.error("支付宝查询投诉详情请求失败 message:{}",  e);
            channelComplaintOrderContext.setRemark("支付宝查询投诉详情请求失败,失败信息" + e.getMessage());
            channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
        }

        return CommonResult.success();
    }

    @Override
    public CommonResult<PageResult<WxComplaintHistoryDto>> queryComplaintHistory(ChannelComplaintOrderContext channelComplaintOrderContext) {
        log.info("AliMerchantComplaintExtPt queryComplaintHistory 请求参数:{}", JsonUtils.toJsonString(channelComplaintOrderContext));
        OrderComplaintDO orderComplaintDO = channelComplaintOrderContext.getOrderComplaintDO();
        try {
            ComplaintOrderQueryDto complaintOrderQueryDto = new ComplaintOrderQueryDto();
            complaintOrderQueryDto.setComplaintId(orderComplaintDO.getComplaintId());
            complaintOrderQueryDto.setPageNo(channelComplaintOrderContext.getOffset());
            complaintOrderQueryDto.setPageSize(channelComplaintOrderContext.getLimit());
            PageResult<OrderComplaintHistoryDO> pageResult = orderComplaintService.queryComplaintHistoryPage(complaintOrderQueryDto);

            List<WxComplaintHistoryDto> list = new ArrayList<>();
            if(CollUtil.isNotEmpty(pageResult.getList())){
                for(OrderComplaintHistoryDO orderComplaintHistoryDO : pageResult.getList()){
                    WxComplaintHistoryDto wxComplaintHistoryDto = new WxComplaintHistoryDto();
                    wxComplaintHistoryDto.setOperator(orderComplaintHistoryDO.getOperator());
                    wxComplaintHistoryDto.setOperateTime(orderComplaintHistoryDO.getOperatorTime());
                    wxComplaintHistoryDto.setOperateDetails(orderComplaintHistoryDO.getOperateDetails());
                    wxComplaintHistoryDto.setOperateType(orderComplaintHistoryDO.getOperateType());

                    OrderComplaintMediaDto mediaDto = new OrderComplaintMediaDto();
                    if(StrUtil.isNotEmpty(orderComplaintHistoryDO.getImageList())){
                        mediaDto.setUrl(Arrays.asList(orderComplaintHistoryDO.getImageList().split(",")));
                    }
                    wxComplaintHistoryDto.setMedias(mediaDto);
                    list.add(wxComplaintHistoryDto);
                }
            }
            PageResult<WxComplaintHistoryDto> result = new PageResult<>();
            result.setPageNo(pageResult.getPageNo());
            result.setPageSize(pageResult.getPageSize());
            result.setPages(pageResult.getPages());
            result.setTotal(pageResult.getTotal());
            result.setList(list);
            return CommonResult.success(result);
        }catch (Exception e) {
            log.error("查询投诉历史请求失败 message:{}", e.getMessage(), e);
            channelComplaintOrderContext.setRemark("查询投诉历史请求失败,失败信息" + e.getMessage());
            channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
        }
        return CommonResult.success();
    }

    @Override
    public CommonResult<OrderComplaintNotifyDto> complaintStatusParse(HttpServletRequest request, ChannelComplaintOrderContext channelComplaintOrderContext) {
        CommonResult<OrderComplaintNotifyDto> orderComplaintNotifyDtoCommonResult = CommonResult.success();
        try {
            // 支付宝配置信息
            CommonResult<AlipayConfig> alipayConfigCommonResult  = aliPayCommonParamsHandle.aliComplaintConfig(channelComplaintOrderContext.getOrderComplaintChannelDO(),
                    channelComplaintOrderContext.isTest());
            if (!alipayConfigCommonResult.isSuccess()) {
                channelComplaintOrderContext.setRemark(alipayConfigCommonResult.getMsg());
                channelComplaintOrderContext.setProcessStatus(false);
            }
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = AliPayApi.toMap(request);
            log.info("支付宝投诉通知明文 {}", JSONUtil.toJsonStr(params));

            OrderComplaintNotifyDto orderComplaintNotifyDto = new OrderComplaintNotifyDto();
            orderComplaintNotifyDto.setCallBackBody(JSONUtil.toJsonStr(params));
            OrderComplaintDO complaintDO = new OrderComplaintDO();
            AliComplaintNotifyResp respData = JsonUtils.parseObject(JSONUtil.toJsonStr(params), AliComplaintNotifyResp.class);
            complaintDO.setComplaintId(respData.getComplaint_id());
            orderComplaintNotifyDto.setOrderComplaint(complaintDO);
            // 回复
            OrderComplaintHistoryDO orderComplaintHistoryDO = new OrderComplaintHistoryDO();
            orderComplaintHistoryDO.setComplaintId(respData.getComplaint_id());
            orderComplaintHistoryDO.setOperator("投诉人");
            orderComplaintHistoryDO.setOperateType("用户回复");
            orderComplaintHistoryDO.setOperateDetails(respData.getReply_content());
            orderComplaintHistoryDO.setOperatorTime(DateUtils.shanghaiDate(respData.getReply_time(),DatePattern.NORM_DATETIME_PATTERN));
            orderComplaintNotifyDto.setOrderComplaintHistoryDO(orderComplaintHistoryDO);

            orderComplaintNotifyDtoCommonResult.setData(orderComplaintNotifyDto);
        }
        catch (Exception e) {
            channelComplaintOrderContext.setProcessStatus(false);
            orderComplaintNotifyDtoCommonResult.setCode(MerchantResultCode.MERCHANT_CHANNEL_CALLBACK_SIGN_ERROR.getCode());
        }
        log.info("支付宝投诉通知回调,解析后的订单数据为 payOrderDO:{}", JsonUtils.toJsonStringNotNull(orderComplaintNotifyDtoCommonResult.getData()));
        return orderComplaintNotifyDtoCommonResult;


    }

    @Override
    public CommonResult<String> queryComplaintNotify(ChannelComplaintOrderContext channelComplaintOrderContext) {
        // log.info(" WxMerchantComplaintExtPt queryComplaintNotify 请求参数:{}", JsonUtils.toJsonString(channelComplaintOrderContext));
        // OrderComplaintChannelDO orderComplaintChannelDO = channelComplaintOrderContext.getOrderComplaintChannelDO();
        // CommonResult<WxPayConfig> wxPayConfigCommonResult = wxPayCommonParamsHandle.wxComplaintConfig(orderComplaintChannelDO,
        //         channelComplaintOrderContext.isTest());
        // if (!wxPayConfigCommonResult.isSuccess()) {
        //     channelComplaintOrderContext.setRemark(wxPayConfigCommonResult.getMsg());
        //     channelComplaintOrderContext.setProcessStatus(false);
        // }
        // WxPayConfig wxPayConfig = wxPayConfigCommonResult.getData();
        //
        // try {
        //
        //     IJPayHttpResponse response = WxPayApi.v3(
        //             RequestMethodEnum.GET,
        //             WxDomainEnum.CHINA.toString(),
        //             ComplaintsApiEnum.COMPLAINTS_NOTIFICATION.toString(),
        //             wxPayConfig.getMchId(),
        //             wxPayConfig.getSerialNo(),
        //             null,
        //             wxPayConfig.getPrivateKeyPath(),
        //             "",
        //             AuthTypeEnum.RSA.getCode()
        //     );
        //
        //     log.info("查询回调通知地址返回参数:{}", response);
        //     if (response.getStatus() == WxPayExtConstant.OK) {
        //         JSONObject resp = JSONUtil.parseObj(response.getBody());
        //         String url = resp.getStr("url");
        //         if(StrUtil.isNotEmpty(url)){
        //             return CommonResult.success(url);
        //         }
        //     }else{
        //         channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
        //         if (StringUtils.hasText(response.getBody())) {
        //             channelComplaintOrderContext.setRemark(response.getBody());
        //         }
        //         else {
        //             channelComplaintOrderContext.setRemark("查询回调通知地址返回错误信息为空,错误码为:" + response.getStatus());
        //         }
        //     }
        //
        // }catch (Exception e) {
        //     e.printStackTrace();
        //     log.error("查询回调通知请求失败 message:{}", e.getMessage(), e);
        //     channelComplaintOrderContext.setRemark("查询回调通知地址请求失败,失败信息" + e.getMessage());
        //     channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
        // }
        return CommonResult.success();
    }

    @Override
    public CommonResult<String> saveComplaintNotify(ChannelComplaintOrderContext channelComplaintOrderContext) {

        // log.info(" WxMerchantComplaintExtPt 请求参数:{}", JsonUtils.toJsonString(channelComplaintOrderContext));
        // OrderComplaintChannelDO orderComplaintChannelDO = channelComplaintOrderContext.getOrderComplaintChannelDO();
        // CommonResult<WxPayConfig> wxPayConfigCommonResult = wxPayCommonParamsHandle.wxComplaintConfig(orderComplaintChannelDO,
        //         channelComplaintOrderContext.isTest());
        // if (!wxPayConfigCommonResult.isSuccess()) {
        //     channelComplaintOrderContext.setRemark(wxPayConfigCommonResult.getMsg());
        //     channelComplaintOrderContext.setProcessStatus(false);
        // }
        // WxPayConfig wxPayConfig = wxPayConfigCommonResult.getData();
        //
        // try {
        //     // 判断是否更新
        //     RequestMethodEnum requestMethodEnum = RequestMethodEnum.POST;
        //     if(orderComplaintChannelDO.getNotifyFlag() != null && orderComplaintChannelDO.getNotifyFlag() == 1){
        //         requestMethodEnum = RequestMethodEnum.PUT;
        //     }
        //
        //     Map<String,String> params = new HashMap<>();
        //     params.put("url",channelComplaintOrderContext.getComplaintNotifyUrl());
        //
        //     IJPayHttpResponse response = WxPayApi.v3(
        //             requestMethodEnum,
        //             WxDomainEnum.CHINA.toString(),
        //             ComplaintsApiEnum.COMPLAINTS_NOTIFICATION.toString(),
        //             wxPayConfig.getMchId(),
        //             wxPayConfig.getSerialNo(),
        //             wxPayConfig.getPayPublicId(),
        //             wxPayConfig.getPrivateKeyPath(),
        //             JSONUtil.toJsonStr(params),
        //             AuthTypeEnum.RSA.getCode()
        //     );
        //
        //     log.info("更新回调通知地址返回参数:{}", response);
        //     // 支付宝支付公钥验证签名
        //     boolean verifySignature = WxPayKit.verifyPublicKeySignature(response, wxPayConfig.getPayPublicPath());
        //     if(verifySignature){
        //         if (response.getStatus() == WxPayExtConstant.OK) {
        //             JSONObject resp = JSONUtil.parseObj(response.getBody());
        //             String url = resp.getStr("url");
        //             if(StrUtil.isNotEmpty(url)){
        //                 return CommonResult.success(url);
        //             }
        //         }else{
        //             channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
        //             if (StringUtils.hasText(response.getBody())) {
        //                 channelComplaintOrderContext.setRemark(response.getBody());
        //             }
        //             else {
        //                 channelComplaintOrderContext.setRemark("更新回调通知地址返回错误信息为空,错误码为:" + response.getStatus());
        //             }
        //         }
        //     }else{
        //         channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
        //         channelComplaintOrderContext.setRemark("更新回调通知地址支付公钥验签失败, " + wxPayConfig.getPayPublicPath());
        //     }
        //
        //
        // }catch (Exception e) {
        //     e.printStackTrace();
        //     log.error("更新回调通知请求失败 message:{}", e.getMessage(), e);
        //     channelComplaintOrderContext.setRemark("更新回调通知地址请求失败,失败信息" + e.getMessage());
        //     channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
        // }
        return CommonResult.success();
    }

    @Override
    public CommonResult<String> replyUser(ChannelComplaintOrderContext channelComplaintOrderContext) {
        log.info(" AliMerchantComplaintExtPt replyUser 请求参数:{}", JsonUtils.toJsonString(channelComplaintOrderContext));
        OrderComplaintChannelDO orderComplaintChannelDO = channelComplaintOrderContext.getOrderComplaintChannelDO();
        OrderComplaintDO orderComplaintDO = channelComplaintOrderContext.getOrderComplaintDO();
        // 支付宝配置信息
        CommonResult<AlipayConfig> alipayConfigCommonResult  = aliPayCommonParamsHandle.aliComplaintConfig(orderComplaintChannelDO,
                channelComplaintOrderContext.isTest());
        if (!alipayConfigCommonResult.isSuccess()) {
            channelComplaintOrderContext.setRemark(alipayConfigCommonResult.getMsg());
            channelComplaintOrderContext.setProcessStatus(false);
        }
        try {
            // 获取AlipayClient
            AlipayClient client = aliPayCommonParamsHandle.initClient(alipayConfigCommonResult.getData());
            // 构造请求参数以调用接口
            AlipaySecurityRiskComplaintReplySendRequest request = new AlipaySecurityRiskComplaintReplySendRequest();
            AlipaySecurityRiskComplaintReplySendModel model = new AlipaySecurityRiskComplaintReplySendModel();
            // 设置投诉id
            model.setComplaintId(orderComplaintDO.getComplaintId());
            // 设置留言内容
            model.setReplyContent(channelComplaintOrderContext.getContent());
            request.setBizModel(model);

            log.info("支付宝投诉回复用户请求参数:{}", JSONUtil.toJsonStr(model));
            AlipaySecurityRiskComplaintReplySendResponse response = client.execute(request);;
            log.info("支付宝投诉回复用户返回参数:{}", JSONUtil.toJsonStr(response));

            if (response.isSuccess() ) {
                log.info("支付宝投诉回复用户成功");
                // 回复历史
                OrderComplaintHistoryDO orderComplaintHistoryDO = new OrderComplaintHistoryDO();
                orderComplaintHistoryDO.setComplaintId(orderComplaintDO.getComplaintId());
                orderComplaintHistoryDO.setOperator("商户");
                orderComplaintHistoryDO.setOperateType("商户留言");
                orderComplaintHistoryDO.setOperateDetails(channelComplaintOrderContext.getContent());
                orderComplaintHistoryDO.setOperatorTime(DateUtils.getCurrentTime());
                channelComplaintOrderContext.setOrderComplaintHistoryDOList(CollUtil.newArrayList(orderComplaintHistoryDO));
            }else{
                channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
                channelComplaintOrderContext.setRemark(response.getSubMsg());
            }
        }catch (Exception e) {
            log.error("支付宝投诉回复用户请求失败 message:{}",  e);
            channelComplaintOrderContext.setRemark("支付宝投诉回复用户请求失败,失败信息" + e.getMessage());
            channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
        }
        return CommonResult.success();
    }

    @Override
    public CommonResult<String> completeComplaint(ChannelComplaintOrderContext channelComplaintOrderContext) {
        log.info(" AliMerchantComplaintExtPt completeComplaint 请求参数:{}", JsonUtils.toJsonString(channelComplaintOrderContext));
        OrderComplaintChannelDO orderComplaintChannelDO = channelComplaintOrderContext.getOrderComplaintChannelDO();
        OrderComplaintDO orderComplaintDO = channelComplaintOrderContext.getOrderComplaintDO();
        // 支付宝配置信息
        CommonResult<AlipayConfig> alipayConfigCommonResult  = aliPayCommonParamsHandle.aliComplaintConfig(orderComplaintChannelDO,
                channelComplaintOrderContext.isTest());
        if (!alipayConfigCommonResult.isSuccess()) {
            channelComplaintOrderContext.setRemark(alipayConfigCommonResult.getMsg());
            channelComplaintOrderContext.setProcessStatus(false);
        }
        try {
            // 获取AlipayClient
            AlipayClient client = aliPayCommonParamsHandle.initClient(alipayConfigCommonResult.getData());
            // 构造请求参数以调用接口
            AlipaySecurityRiskComplaintProcessFinishRequest request = new AlipaySecurityRiskComplaintProcessFinishRequest();
            AlipaySecurityRiskComplaintProcessFinishModel model = new AlipaySecurityRiskComplaintProcessFinishModel();
            // 设置投诉id列表
            model.setIdList(CollUtil.newArrayList(Long.valueOf(orderComplaintDO.getComplaintId())));
            // 设置投诉处理结果码
            model.setProcessCode(aliPayCommonParamsHandle.resultType(channelComplaintOrderContext.getType()));
            // 设置备注
            model.setRemark(channelComplaintOrderContext.getContent());
            if(CollUtil.isNotEmpty(channelComplaintOrderContext.getImgUrls())){
                // 设置图片文件列表
                List<ImgFile> imgFileList = aliPayCommonParamsHandle.getComplaintImgUrls(channelComplaintOrderContext.getImgUrls(),alipayConfigCommonResult.getData());
                model.setImgFileList(imgFileList);
            }
            request.setBizModel(model);

            log.info("支付宝投诉处理请求参数:{}", JSONUtil.toJsonStr(model));
            AlipaySecurityRiskComplaintProcessFinishResponse response = client.execute(request);
            log.info("支付宝投诉处理返回参数:{}", JSONUtil.toJsonStr(response));
            if (response.isSuccess() ) {
                log.info("支付宝投诉处理成功");
                OrderComplaintHistoryDO orderComplaintHistoryDO = new OrderComplaintHistoryDO();
                orderComplaintHistoryDO.setComplaintId(orderComplaintDO.getComplaintId());
                orderComplaintHistoryDO.setOperator("商户");
                orderComplaintHistoryDO.setOperateType("商户投诉处理");
                orderComplaintHistoryDO.setOperateDetails(channelComplaintOrderContext.getContent());
                orderComplaintHistoryDO.setOperatorTime(DateUtils.getCurrentTime());
                if(CollUtil.isNotEmpty(channelComplaintOrderContext.getImgUrls())){
                    orderComplaintHistoryDO.setImageList(CollUtil.join(channelComplaintOrderContext.getImgUrls(),","));
                }
                channelComplaintOrderContext.setOrderComplaintHistoryDOList(CollUtil.newArrayList(orderComplaintHistoryDO));
            }else{
                channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
                channelComplaintOrderContext.setRemark(response.getSubMsg());
            }
        }catch (Exception e) {
            log.error("支付宝投诉回复用户请求失败 message:{}",  e);
            channelComplaintOrderContext.setRemark("支付宝投诉回复用户请求失败,失败信息" + e.getMessage());
            channelComplaintOrderContext.setProcessStatus(Boolean.FALSE);
        }
        return CommonResult.success();

    }

    @Override
    public CommonResult<String> updateComplaintProgress(ChannelComplaintOrderContext channelComplaintOrderContext) {
        return CommonResult.success();

    }

    @Override
    public String callBackResponse(CommonResult commonResult) {
        if (commonResult.isSuccess()) {
            return "SUCCESS";
        }
        else {
            return "FAIL";
        }
    }


    private WxComplaintDetailResp.ComplaintOrderInfo getOutTradeOrderInfo(List<WxComplaintDetailResp.ComplaintOrderInfo> list){

        if(CollUtil.isEmpty(list)){
            return null;
        }
        return list.get(0);
    }




    public OrderComplaintDO formatDetailResp(AlipaySecurityRiskComplaintInfoQueryResponse aliComplaintDetailResp,AlipayConfig alipayConfig) throws Exception {
        OrderComplaintDO orderComplaintDO = new OrderComplaintDO();
        if(StrUtil.isNotEmpty(aliComplaintDetailResp.getContact())){
            orderComplaintDO.setPhone(aliComplaintDetailResp.getContact());
        }
        orderComplaintDO.setDetail(aliComplaintDetailResp.getComplainContent());
        orderComplaintDO.setCreateTime(DateUtils.shanghaiDate(DateUtil.format(aliComplaintDetailResp.getGmtComplain(), DatePattern.NORM_DATETIME_PATTERN),DatePattern.NORM_DATETIME_PATTERN));
        orderComplaintDO.setAppId(aliComplaintDetailResp.getOppositePid());
        orderComplaintDO.setComplaintId(aliComplaintDetailResp.getId().toString());
        orderComplaintDO.setWxOrderNo(aliComplaintDetailResp.getTradeNo());
        orderComplaintDO.setAmount(new BigDecimal(aliComplaintDetailResp.getComplainAmount()));
        orderComplaintDO.setType(2);
        orderComplaintDO.setStatus(aliPayCommonParamsHandle.complaintStatusType(aliComplaintDetailResp.getStatus()));
        // 已退款
        if(StrUtil.isNotEmpty(aliComplaintDetailResp.getProcessCode()) && aliComplaintDetailResp.getProcessCode().equals("REFUND")){
            orderComplaintDO.setRefunded(1);
        }
        // 获取订单SN
        PayOrderDO payOrderDO = payOrderService.queryWxAssociatedOrder(orderComplaintDO.getWxOrderNo());
        if(payOrderDO != null){
            orderComplaintDO.setSn(payOrderDO.getSn());
            orderComplaintDO.setPayOrderNo(payOrderDO.getPayOrderNo());
            orderComplaintDO.setChannelCode(payOrderDO.getChannelCode());
            orderComplaintDO.setProviderCode(payOrderDO.getProviderCode());
        }
        return orderComplaintDO;
    }

    /**
     * 支付宝投诉详情本地序列化
     * @param aliComplaintDetailResp  支付宝投诉详情
     * @return
     * @throws Exception
     */
    public OrderComplaintDO formatDetailResp(ComplaintInfoQueryResponse aliComplaintDetailResp,OrderComplaintChannelDO orderComplaintChannelDO) throws Exception {

        OrderComplaintDO orderComplaintDO = new OrderComplaintDO();
        if(StrUtil.isNotEmpty(aliComplaintDetailResp.getContact())){
            orderComplaintDO.setPhone(aliComplaintDetailResp.getContact());
        }
        orderComplaintDO.setDetail(aliComplaintDetailResp.getComplainContent());
        orderComplaintDO.setCreateTime(DateUtils.shanghaiDate(DateUtil.format(aliComplaintDetailResp.getGmtComplain(), DatePattern.NORM_DATETIME_PATTERN),DatePattern.NORM_DATETIME_PATTERN));
        orderComplaintDO.setAppId(aliComplaintDetailResp.getOppositePid());
        orderComplaintDO.setComplaintId(aliComplaintDetailResp.getId().toString());
        orderComplaintDO.setWxOrderNo(aliComplaintDetailResp.getTradeNo());
        orderComplaintDO.setAmount(new BigDecimal(aliComplaintDetailResp.getComplainAmount()));
        orderComplaintDO.setStatus(aliPayCommonParamsHandle.complaintStatusType(aliComplaintDetailResp.getStatus()));
        orderComplaintDO.setChannelId(orderComplaintChannelDO.getId());
        orderComplaintDO.setType(orderComplaintChannelDO.getType());
        // 已退款
        if(StrUtil.isNotEmpty(aliComplaintDetailResp.getProcessCode()) && aliComplaintDetailResp.getProcessCode().equals("REFUND")){
            orderComplaintDO.setRefunded(1);
        }

        // 获取订单SN
        PayOrderDO payOrderDO = payOrderService.queryWxAssociatedOrder(orderComplaintDO.getWxOrderNo());
        if(payOrderDO != null){
            orderComplaintDO.setSn(payOrderDO.getSn());
            orderComplaintDO.setPayOrderNo(payOrderDO.getPayOrderNo());
            orderComplaintDO.setChannelCode(payOrderDO.getChannelCode());
            orderComplaintDO.setProviderCode(payOrderDO.getProviderCode());
        }
        return orderComplaintDO;
    }



}
